package com.smarttourism.service;

import com.smarttourism.common.core.redis.RedisCache;
import com.smarttourism.domain.Roomorder;

import com.smarttourism.domain.SHX.SHXRoom;
import com.smarttourism.mapper.RoomorderMapper;
import com.smarttourism.mapper.SHXRoomMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoomorderService {
    @Autowired
    private RoomorderMapper roomorderMapper;
    @Autowired
    private SHXRoomMapper shxRoomMapper;
    @Autowired
    private RedisCache redisCache;

    private RedisTemplate redisTemplate;


    public void InitRoomOrderList() {
        List<Roomorder> roomorderList = RoomOrderList("-1", -1);
        for (Roomorder roomorder : roomorderList) {
            redisCache.<Roomorder>setCacheMapValue("RoomOrderList", "status" + roomorder.getStatus() + "rname" + roomorder.getRname() + "id" + roomorder.getId(), roomorder);
        }
    }

    public List<Roomorder> RoomOrderList(String rname, Integer statusId) {
        List<Roomorder> roomOrders = roomorderMapper.findAllRoomOrders(rname, statusId);
        if (roomOrders != null) {
            for (Roomorder roomOrder : roomOrders) {
                if (roomOrder != null) {
//                    roomOrder.setRoomInfo(shxRoomMapper.selectRoomByRnum(roomOrder.getRNum()));
                    SHXRoom room = shxRoomMapper.selectRoomByRnum(roomOrder.getRNum());
                    if (room != null) {
                        room.setRoomStatus(shxRoomMapper.selectInfoRoomStatusById(room.getId()));
                        room.setRoomType(shxRoomMapper.selectInfoRoomTypeById(room.getTypeId()));
                    }
                    roomOrder.setRoomInfo(room);
                    roomOrder.setRoomOrderStatus(roomorderMapper.selectOrderStatusById(roomOrder.getStatus()));
                }


            }
        }
        return roomOrders;
    }


    @Transactional
    public int addRoomOrder(Roomorder roomorder) {
        // 新增订单信息
        int i = roomorderMapper.insertSelective(roomorder);
        // 修改订单中的房间状态为3预定
        shxRoomMapper.updateStatusToBookedByNum(roomorder.getRNum());
        return i;

    }


    public List<SHXRoom> findFreeRooms() {
        return shxRoomMapper.findFreeRooms();
    }

    // 逻辑删除
    public int deleteOrderById(int id) {
        return roomorderMapper.updateDeleteOrderById(id);
    }

    // 修改订单状态
    @Transactional
    public int updateOrderStatus(int status, int id) {
        if (status == 3) {
            // 如果修改订单状态为退订 则修改房间状态为净房子
            Roomorder roomorder = roomorderMapper.selectByPrimaryKey((long) id);
            shxRoomMapper.updateStatusToFreeByNum(roomorder.getRNum());
        }
        int i = roomorderMapper.updateOrderStatusById(status, id);
        return i;
    }


}
